const express = require('express');
const multer = require('multer');
const Tripo3DClient = require('../services/tripo3dClient');
const router = express.Router();

// 配置文件上传
const storage = multer.memoryStorage();
const upload = multer({
  storage: storage,
  limits: {
    fileSize: 10 * 1024 * 1024, // 限制文件大小为10MB
  },
  fileFilter: (req, file, cb) => {
    // 只允许图片文件
    if (file.mimetype.startsWith('image/')) {
      cb(null, true);
    } else {
      cb(new Error('只支持图片文件！'), false);
    }
  }
});

const tripo3dClient = new Tripo3DClient();

/**
 * @swagger
 * /api/generate-from-url:  
 *   post:
 *     summary: 从图片URL生成3D模型
 *     requestBody:
 *       required: true
 *       content:
 *         application/json:
 *           schema:
 *             type: object
 *             properties:
 *               image_url:  
 *                 type: string
 *                 description: 图片的URL地址
 *               options:
 *                 type: object
 *                 description: 额外的生成选项
 *     responses:
 *       200:  
 *         description: 成功创建生成任务
 *       400:  
 *         description: 请求参数错误
 */
router.post('/generate-from-url', async (req, res) => {
  try {
    const { image_url, options = {} } = req.body;
    
    if (!image_url) {
      return res.status(400).json({ error: '缺少必要参数: image_url' });
    }
    
    const result = await tripo3dClient.generate3DFromImage(image_url, options);
    res.json({ success: true, data: result });
  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: error.response?.data?.message || error.message 
    });
  }
});

/**
 * @swagger
 * /api/generate-from-upload:  
 *   post:
 *     summary: 上传图片并生成3D模型
 *     requestBody:
 *       required: true
 *       content:
 *         multipart/form-data:
 *           schema:
 *             type: object
 *             properties:
 *               image:  
 *                 type: string
 *                 format: binary
 *                 description: 要上传的图片文件
 *     responses:
 *       200:  
 *         description: 成功创建生成任务
 *       400:  
 *         description: 请求参数错误
 */
router.post('/generate-from-upload', upload.single('image'), async (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({ error: '没有上传图片文件' });
    }
    
    const { options = {} } = req.body;
    let parsedOptions = {};
    
    // 如果options是JSON字符串，则解析它
    if (typeof options === 'string') {
      try {
        parsedOptions = JSON.parse(options);
      } catch (e) {
        // 如果解析失败，使用空对象
      }
    } else if (typeof options === 'object') {
      parsedOptions = options;
    }
    
    const result = await tripo3dClient.generate3DFromUploadedImage(
      req.file.buffer, 
      req.file.mimetype,
      parsedOptions
    );
    
    res.json({ success: true, data: result });
  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: error.response?.data?.message || error.message 
    });
  }
});

/**
 * @swagger
 * /api/task-status/{taskId}:
 *   get:
 *     summary: 获取生成任务的状态
 *     parameters:
 *       - in: path
 *         name: taskId
 *         required: true
 *         schema:
 *           type: string
 *         description: 任务ID
 *     responses:
 *       200:  
 *         description: 返回任务状态
 *       404:  
 *         description: 任务不存在
 */
router.get('/task-status/:taskId', async (req, res) => {
  try {
    const { taskId } = req.params;
    const status = await tripo3dClient.getTaskStatus(taskId);
    res.json({ success: true, data: status });
  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: error.response?.data?.message || error.message 
    });
  }
});

/**
 * @swagger
 * /api/download-model/{modelId}:
 *   get:
 *     summary: 下载生成的3D模型
 *     parameters:
 *       - in: path
 *         name: modelId
 *         required: true
 *         schema:
 *           type: string
 *         description: 模型ID
 *       - in: query
 *         name: format
 *         schema:
 *           type: string
 *           default: glb
 *         description: 模型格式 (glb, obj, stl等)
 *     responses:
 *       200:  
 *         description: 返回3D模型文件
 *       404:  
 *         description: 模型不存在
 */
router.get('/download-model/:modelId', async (req, res) => {
  try {
    const { modelId } = req.params;
    const { format = 'glb' } = req.query;
    
    const modelData = await tripo3dClient.downloadModel(modelId, format);
    
    // 设置响应头
    res.setHeader('Content-Type', `model/${format}`);
    res.setHeader('Content-Disposition', `attachment; filename=${modelId}.${format}`);
    res.setHeader('Content-Length', modelData.length);
    
    res.send(modelData);
  } catch (error) {
    res.status(500).json({ 
      success: false, 
      error: error.response?.data?.message || error.message 
    });
  }
});

/**
 * @swagger
 * /api/health:
 *   get:
 *     summary: 检查API健康状态
 *     responses:
 *       200:  
 *         description: API正常
 */
router.get('/health', (req, res) => {
  res.json({
    success: true,
    message: 'Tripo3D API 集成服务运行正常',
    timestamp: new Date().toISOString()
  });
});

module.exports = router;